<template>
	<a-row :gutter="10" :body-style="{ 'padding-bottom': '0px' }" class="mb-2">
		<a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
			<a-card>
				<a-space>
					<a-input-search placeholder="请输入内容" v-model:value="search"
									@search="refresh()"></a-input-search>
					<a-button v-show="!props.systemFlag" type="primary" @click="add">新增</a-button>
				</a-space>
			</a-card>
		</a-col>
	</a-row>

	<a-row :gutter="10" :body-style="{ 'padding-bottom': '0px' }" class="mb-2">
		<a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
			<a-card>
				<h-table :rowClick="rowClick" :paged="false" ref="tableRef" :columns="columns"
						 :data="queryCompVersionList" :height="100">
				</h-table>
			</a-card>
		</a-col>
	</a-row>

	<input type="file" ref="uploadInput" @change="progress(uploadInput.files[0])" style="display: none"/>

	<a-modal v-model:open="compDiag.visible" @cancel="compDiag.visible = false" :closable="false" @ok="saveCompVersion">
		<a-form :model="compDiag">
			<a-form-item label="组件版本">
				<a-input v-model:value="compDiag.compVersion"></a-input>
			</a-form-item>
			<a-form-item label="组件描述">
				<a-input v-model:value="compDiag.compDesc"></a-input>
			</a-form-item>
		</a-form>
	</a-modal>

	<a-modal v-model:open="compObjectDiag" :destroyOnClose="true" :width="1000" :closable="false"
			 @cancel="compObjectDiag = false" @ok="saveObj">

		<ProcessCompObjectManager :compCode="currentCompCode" :compVersion="currentCompVersion"
								  :readonly="props.systemFlag"
								  :connected="false"
								  ref="objManager"/>
	</a-modal>

	<a-modal v-model:open="logDiag" :width="1000" :footer="null" :closable="false" @cancel="logDiag = false"
			 @ok="logDiag = false">
		<div ref="logInput" style="width: 100%; height: 150px; text-align: left"></div>
	</a-modal>
	<FloatToolbar :lf="lf" :config="buildLogConfig"
				  v-show="buildDiag" ref="floatToolbar"></FloatToolbar>
</template>

<script setup>
import {h} from 'vue'
import ProcessCompObjectManager from './ProcessCompObjectManager.vue'

import * as monaco from 'monaco-editor'
import {toRaw, getCurrentInstance, defineExpose} from 'vue'
import {message} from 'ant-design-vue'

import FloatToolbar from '@/views/process/engine/floatToolbar.vue'
import processCompVersionApi from '@/api/comp/processCompVersionApi'
import processCompApi from '@/api/comp/processCompApi'
import downloadUtil from "@/utils/downloadUtil";
import processTestApi from "@/api/process/processTestApi";
import {customMountFunc} from "@/views/process/engine/functions.js";

const currentCompVersion = ref();
let monacoEditor = null;
const buildDiag = ref(false);
const currentCompCode = ref();
const search = ref();
const logInput = ref();
const objManager = ref();

const buildLogConfig = ref({
	toolbarViewFlag: false,
	paramViewFlag: false,
	logContainerConfig: {
		width: '100%',
		'height': '250px'
	}
})
const lf = ref({})

customMountFunc(lf.value)

const floatToolbar = ref();
const logDiag = ref(false)
const props = defineProps(["compCode", "systemFlag"])
const compObjectDiag = ref(false);
const fileList = ref([]);
const columns = ref([
	{
		title: '编码',
		dataIndex: 'compCode',
		key: 'compCode',
		ellipsis: true,
	},
	{
		title: '版本',
		dataIndex: 'compVersion',
		key: 'compVersion',
		ellipsis: true,
	},
	{
		title: '描述',
		dataIndex: 'compDesc',
		key: 'compDesc',
		width: 200,
		ellipsis: true,
	},
	{
		title: '启停状态',
		dataIndex: 'disableFlag',
		key: 'disableFlag',
		ellipsis: true,
		mapping: [{
			key: '1',
			value: '停用'
		}, {
			key: '0',
			value: '启用'
		}],
	},
	{
		title: '构建状态',
		dataIndex: 'buildStatus',
		key: 'buildStatus',
		click: (field, record) => {
			buildStatusMessage(record)
		},
		mapping: [{
			key: '1',
			value: '构建中'
		},
			{
				key: '2',
				value: '构建完成'
			},
			{
				key: '3',
				value: '构建失败'
			},
			{
				key: null,
				value: '无构建信息'
			},
		],
		ellipsis: true,
	}, {
		title: '操作',
		dataIndex: 'action',
		key: 'action',
		width: 550,
		ellipsis: true,
		fixed: 'right',
		buttonList: [
			{
				click: (field, record) => {
					setStatusFlag(record)
				},
				render: (record) => {
					if (record.systemFlag) {
						return null;
					}
					return record.disableFlag == '0' ? '停用' : '启用';
				}
			},
			{
				type: 'primary',
				click: (field, record) => {
					if (record.systemFlag) {
						view(record)
					} else {
						edit(record)
					}

				},
				render: (record) => {

					return record.systemFlag ? "查看" : "编辑";
				}
			},
			{
				click: (field, record) => {

					if (record.systemFlag) {
						viewPackage(record)
					} else {
						editPackage(record)
					}
				},
				type: 'primary',
				render: (record) => {
					return record.systemFlag ? "查看包" : "编辑包";
				}
			},
			{
				click: (field, record) => {
					download(record)
				},
				render: (record) => {
					return record.systemFlag ? null : "下载包";
				}
			},
			{
				click: (field, record) => {

					upload(record)
				},
				render: (record) => {
					return record.systemFlag ? null : "上传包";
				}
			},
			{
				click: (field, record) => {
					remove(record)
				},
				render: (record) => {
					return record.systemFlag ? null : "删除";
				}
			},
			{
				click: (field, record) => {
					pack(record)
				},
				render: (record) => {
					return record.systemFlag ? null : "构建";
				}
			},
		]
	},

])
const uploadInput = ref()

const compDiag = ref({
	visible: false,
	viewFlag: false,
	compVersion: '',
	compCode: '',
	id: null,
	compDesc: null
	// compFile: null
})


const beforeUpload = () => {
	fileList.value = []
	return false;
}

const saveObj = async () => {
	if (props.systemFlag) {
		compObjectDiag.value = false
		return;
	}
	let compFile = await objManager.value.getFile()
	await processCompApi.saveFile({
		compVersion: currentCompVersion.value,
		compCode: currentCompCode.value,
		compFile: compFile
	})

	compObjectDiag.value = false
	refresh();
}

const tableRef = ref();

const refresh = () => {
	tableRef.value.refresh(true)
}
defineExpose({
	refresh
})
const remove = async (record) => {
	await processCompVersionApi.removeById({
		compVersion: record.compVersion,
		compCode: record.compCode,
		id: record.id
	})
	refresh()
}

//弹出框框
const pack = async (record) => {
	let tid = await processTestApi.getTid({})

	buildDiag.value = true;
	floatToolbar.value.closeSession();
	await floatToolbar.value.openRunDraw(tid);

	await processCompVersionApi.rebuild({
		compVersion: record.compVersion,
		compCode: record.compCode,
		id: record.id,
		tid: tid
	})
	message.info('正在自动构建，请关注构建状态');
}
const add = () => {
	compDiag.value.visible = true
}
const view = (row) => {
	compDiag.value.compCode = row.compCode
	compDiag.value.id = row.id
	compDiag.value.compDesc = row.compDesc
	compDiag.value.systemFlag = row.systemFlag
	compDiag.value.viewFlag = true
	compDiag.value.compVersion = row.compVersion
	compDiag.value.visible = true
}
const download = async (row) => {
	let blob = await processCompApi.getFile(row.compCode, row.compVersion)
	let filename = row.compCode + "@" + row.compVersion + "@.zip"
	downloadUtil.resultDownload(blob, filename);
}
const clearLog = () => {
	monacoEditor.setValue('')
}

const viewPackage = async (row) => {
	editPackage(row)
}
const editPackage = (row) => {
	rowClick(row);
	compObjectDiag.value = true
	// nextTick(() => {
	// 	objManager.loadZip(row.compCode, row.compVersion, false, false)
	// })
}
const rowClick = (row) => {
	currentCompVersion.value = row.compVersion
	currentCompCode.value = row.compCode

}
const buildStatusMessage = (row) => {
	logDiag.value = true
	nextTick(() => {
		initMonaco()
		clearLog()
		getBuildLog(row)
	})
}

const getBuildLog = async (row) => {
	const d = await processCompVersionApi.getLastByCodeAndVersion({
		compVersion: row.compVersion,
		compCode: row.compCode
	})
	if (d && d.buildContent) {
		monacoEditor.setValue(d.buildContent)
	}
}
const initMonaco = () => {
	if (monacoEditor == null) {
		monacoEditor = monaco.editor.create(logInput.value, {
			theme: 'vs-dark', // 主题
			value: '', // 默认显示的值
			language: 'log',
			folding: true, // 是否折叠
			foldingHighlight: true, // 折叠等高线
			foldingStrategy: 'indentation', // 折叠方式  auto | indentation
			showFoldingControls: 'always', // 是否一直显示折叠 always | mouseover
			disableLayerHinting: true, // 等宽优化
			emptySelectionClipboard: false, // 空选择剪切板
			selectionClipboard: false, // 选择剪切板
			automaticLayout: true, // 自动布局
			codeLens: false, // 代码镜头
			scrollBeyondLastLine: false, // 滚动完最后一行后再滚动一屏幕
			colorDecorators: true, // 颜色装饰器
			accessibilitySupport: 'off', // 辅助功能支持  "auto" | "off" | "on"
			lineNumbers: 'on', // 行号 取值： "on" | "off" | "relative" | "interval" | function
			lineNumbersMinChars: 5, // 行号最小字符   number
			enableSplitViewResizing: false,
			readOnly: false //是否只读  取值 true | false
		})
	}
}

const upload = () => {
	uploadInput.value.click();
}

const progress = async (file) => {
	let reader = new FileReader()
	// abort none 中断读取
	// readAsBinaryString file 将文件读取为二进制码，通常我们将它传送到后端，后端可以通过这段字符串存储文件
	// readAsDataURL file 将文件读取为 DataURL，一段以 data: 开头的字符串，这段字符串的实质就是 Data URL，Data URL是一种将小文件直接嵌入文档的方案。这里的小文件通常是指图像与 html 等格式的文件
	// readAsText file, [encoding] 将文件读取为文本，读取的结果即是这个文本文件中的内容
	reader.readAsDataURL(file)
	// onabort 中断时触发
	// onerror 出错时触发
	// onload 文件读取成功完成时触发
	// onloadend 读取完成触发，无论成功或失败
	// onloadstart 读取开始时触发
	// onprogress 读取中
	reader.onload = (e) => {
		// 读取文件内容
		// s.compDiag.icon = e.target.result;
		saveFile(e.target.result)
		// s.svgToBase64();
		// 接下来可对文件内容进行处理
	}
}

const saveFile = async (file) => {
	await processCompApi.saveFile({
		compVersion: currentCompVersion.value,
		compCode: currentCompCode.value,
		compFile: file
	})
	message.success("上传成功");

}
const setStatusFlag = async (row) => {
	await processCompVersionApi.setStatusFlag({
		id: row.id,
		disableFlag: row.disableFlag == '1' ? '0' : '1'
	})
	refresh()
}
const edit = async (row) => {
	const data = await processCompVersionApi.getById({
		id: row.id,
		version: row.version
	})
	compDiag.value = data;
	compDiag.value.visible = true
}
const saveCompVersion = async () => {
	if (compDiag.value.viewFlag) {
		compDiag.value.viewFlag = false
		compDiag.value.visible = false
		return
	}
	if (!props.compCode) {
		message.error('错误操作，没有获取到组件编码')
		return
	}
	compDiag.value.compCode = props.compCode

	if (!compDiag.value.compVersion) {
		message.error('请输入组件版本')
		return
	}
	// if (!compDiag.compFile) {
	//   $message.error('请选择组件包');
	//   return;
	// }
	await processCompVersionApi.save(compDiag.value)

	compDiag.value = {};
	compDiag.value.visible = false
	refresh()
}
const queryCompVersionList = async () => {
	const data = await processCompVersionApi.queryCompVersionList({
		compCode: props.compCode
	})
	return data;
}
</script>

<style scoped>
.upload-demo {
	display: inline;
}
</style>
